package com.imachen.ymcc.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.imachen.ymcc.domain.PayFlow;
import com.imachen.ymcc.domain.PayOrder;
import com.imachen.ymcc.dto.PayNotifyLocalTxParamDto;
import com.imachen.ymcc.enums.GlobalExceptionCode;
import com.imachen.ymcc.mapper.PayOrderMapper;
import com.imachen.ymcc.service.IPayFlowService;
import com.imachen.ymcc.service.IPayOrderService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.imachen.ymcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author imachen
 * @since 2022-10-16
 */
@Service
@Slf4j
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {

    @Autowired
    private IPayFlowService payFlowService;

    @Override
    public PayOrder selectPayByOrderNo(String orderNo) {
        return selectOne(new EntityWrapper<PayOrder>().eq("order_no",orderNo));
    }

    /**
     * 课程异步通知 修支付单状态 和 保存支付流水
     * @param payNotifyLocalTxParamDto
     */
    @Override
    public void asyncNotifyHandler(PayNotifyLocalTxParamDto payNotifyLocalTxParamDto) {
        PayFlow payFlow = payNotifyLocalTxParamDto.getPayFlow();
        PayOrder payOrder = payNotifyLocalTxParamDto.getPayOrder();

        // 查询订单是否存在
        PayOrder payOrderTemp = selectPayByOrderNo(payOrder.getOrderNo());
        AssertUtil.isNotNull(payOrderTemp, GlobalExceptionCode.PAY_ORDER_IS_NULL_ERROR);

        synchronized (payOrder.getOrderNo()) {
            if (PayOrder.WAIT_PAY_STATUS.equals(payOrderTemp.getPayStatus())){
                // 修改订单状态
                updateById(payOrder);
                // 保存支付流水信息
                payFlowService.insert(payFlow);
            }
        }
    }


    /**
     * 延迟消息取消订单
     * @param orderNo
     * @param payOrder
     */
    @Override
    public void cancelPayOrder(String orderNo, PayOrder payOrder) {
        try {
            // 关闭支付宝接口
            AlipayTradeCloseResponse close = Factory.Payment.Common().close(orderNo);
            if ( !close.code.equals("10000")) {
                // 关闭失败则是支付成功 会在支付回调接口中进行退款处理
                log.error("订单关闭失败，订单号为：{}", orderNo);
            }
            // 修改支付单状态
            payOrder.setPayStatus(PayOrder.CANCEL_PAY_STATUS);
            updateById(payOrder);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
